package com.diboot.core.methods;

import com.baomidou.mybatisplus.core.injector.AbstractMethod;
import com.baomidou.mybatisplus.core.metadata.TableInfo;
import com.baomidou.mybatisplus.core.toolkit.sql.SqlScriptUtils;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlSource;

import static com.diboot.core.methods.RecycleBinSqlMethod.SELECT_PAGE_IN_RECYCLE_BIN;

public class SelectPageInRecycleBin extends AbstractMethod {
    public SelectPageInRecycleBin() {
        this(SELECT_PAGE_IN_RECYCLE_BIN.name());
    }

    public SelectPageInRecycleBin(String name) {
        super(name);
    }
    @Override
    public MappedStatement injectMappedStatement(Class<?> mapperClass, Class<?> modelClass, TableInfo tableInfo) {
        String sql = String.format(SELECT_PAGE_IN_RECYCLE_BIN.getSql(), this.sqlFirst(), this.sqlSelectColumns(tableInfo, true), tableInfo.getTableName(), this.sqlWhereEntityWrapper(true, tableInfo), this.sqlOrderBy(tableInfo), this.sqlComment());
        SqlSource sqlSource = this.languageDriver.createSqlSource(this.configuration, sql, modelClass);
        return this.addSelectMappedStatementForTable(mapperClass, this.methodName, sqlSource, tableInfo);
    }

    @Override
    protected String sqlWhereEntityWrapper(boolean newLine, TableInfo table) {
        String sqlScript;
        sqlScript = table.getAllSqlWhere(true, true, false,"ew.entity.");
        sqlScript = SqlScriptUtils.convertIf(sqlScript, String.format("%s != null", "ew.entity"), true);
        sqlScript = sqlScript + "\n AND NOT (" + table.getLogicDeleteSql(false, true) + ") \n";
        String normalSqlScript = SqlScriptUtils.convertIf(String.format("AND ${%s}", "ew.sqlSegment"), String.format("%s != null and %s != '' and %s", "ew.sqlSegment", "ew.sqlSegment", "ew.nonEmptyOfNormal"), true);
        normalSqlScript = normalSqlScript + "\n";
        normalSqlScript = normalSqlScript + SqlScriptUtils.convertIf(String.format(" ${%s}", "ew.sqlSegment"), String.format("%s != null and %s != '' and %s", "ew.sqlSegment", "ew.sqlSegment", "ew.emptyOfNormal"), true);
        sqlScript = sqlScript + normalSqlScript;
        sqlScript = SqlScriptUtils.convertChoose(String.format("%s != null", "ew"), sqlScript, table.getLogicDeleteSql(false, true));
        sqlScript = SqlScriptUtils.convertWhere(sqlScript);
        return newLine ? "\n" + sqlScript : sqlScript;
    }
}
